package com.beijiteshop.shop.ui.detail.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Observer
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.ext.databinding.inflateBinding
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.shop.R
import com.beijiteshop.shop.app.PageIndex
import com.beijiteshop.shop.base.FragmentContainerActivity
import com.beijiteshop.shop.databinding.DialogSpecsSelectionBinding
import com.beijiteshop.shop.model.api.request.AddShopCarRequest
import com.beijiteshop.shop.model.api.response.ProductBean
import com.beijiteshop.shop.model.api.response.ProductDetailBean
import com.beijiteshop.shop.model.entity.CheckBoxEntity
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.detail.TextFlexBoxRVHelper
import com.beijiteshop.shop.ui.order.fragment.OrderConfirmFragment
import com.beijiteshop.shop.ui.shopcar.vm.ShopCarVM
import com.beijiteshop.shop.utils.SpecColorUtil
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import org.koin.android.viewmodel.ext.android.viewModel


/**
 * @Author LiaoZhongKai
 * @Date 2021/3/5 10:27
 * @Description 商品规格选择框
 */
class SpecsSelectionDialog : BottomSheetDialogFragment(){

    companion object{
        private const val BUNDLE_DETAIL = "bundle_detail"
        private const val BUNDLE_PRODUCT = "bundle_product"

        fun newInstance(productDetailBean: ProductDetailBean, productBean: ProductBean): SpecsSelectionDialog{
            val dialog = SpecsSelectionDialog()
            dialog.arguments = Bundle().apply {
                putParcelable(BUNDLE_DETAIL,productDetailBean)
                putParcelable(BUNDLE_PRODUCT,productBean)
            }
            return dialog
        }

    }

    private lateinit var mBinding: DialogSpecsSelectionBinding

    private var mProductDetailBean: ProductDetailBean? = null
    private var mProductBean: ProductBean? = null
    private var mOnSpecColorChangeListener: OnSpecColorChangeListener? = null
    private val mShopCarVM: ShopCarVM by viewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NORMAL,R.style.TransBgBottomSheet)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = inflateBinding(inflater)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        initEvent()
        initRV()
    }

    private fun initData(){
        mProductBean = arguments?.getParcelable(BUNDLE_PRODUCT)
        mProductDetailBean = arguments?.getParcelable(BUNDLE_DETAIL)

        mProductDetailBean?.let {
            mBinding.detailBean = it
        }
        mProductBean?.let {
            mBinding.product = it
        }
    }

    private fun initRV(){
        mBinding.specsProductColorRv.itemAnimator = null
        mBinding.specsProductSpecsRv.itemAnimator = null

        mProductDetailBean?.let {
            //颜色
            if (it.colors.isNullOrEmpty()){
                mBinding.specsProductColorCl.visibility = View.GONE
            }else{
                mBinding.specsProductColorCl.visibility = View.VISIBLE
                //颜色
                val checkBoxEntities = mutableListOf<CheckBoxEntity<String>>()
                it.colors.forEachIndexed { index,value ->
                    checkBoxEntities.add(CheckBoxEntity(mProductBean?.color == value,value))
                }
                TextFlexBoxRVHelper.bind(requireContext(),
                    mBinding.specsProductColorRv,
                    checkBoxEntities,
                    R.drawable.bg_product_color_selector,
                    R.color.text_dark) { index, data ->
                    mProductBean?.color = data
                    mOnSpecColorChangeListener?.onChanged(mProductBean?.spec,data)
                }
            }

            //规格
            if (it.specifications.isNullOrEmpty()){
                if (it.specification.isNullOrEmpty()){
                    mBinding.specsProductSpecsCl.visibility = View.GONE
                }else if (!it.specification.isNullOrEmpty()){
                    mBinding.specsProductSpecsTextTv
                    TextFlexBoxRVHelper.bind(requireContext(),
                        mBinding.specsProductSpecsRv,
                        mutableListOf(CheckBoxEntity(true,it.specification!!)),
                        R.drawable.bg_product_specs_selector,
                        R.color.colorWhite) {index, data ->
                            mProductBean?.spec = data
                            mOnSpecColorChangeListener?.onChanged(data,mProductBean?.color)
                    }
                }
            }else{
                val enetities = mutableListOf<CheckBoxEntity<String>>()
                it.specifications.forEachIndexed { index, s ->
                    enetities.add(CheckBoxEntity(mProductBean?.spec == s,s))
                }
                TextFlexBoxRVHelper.bind(requireContext(),
                    mBinding.specsProductSpecsRv,
                    enetities,
                    R.drawable.bg_product_specs_selector,
                    R.color.colorWhite) {index, data ->
                        mProductBean?.spec = data
                        mOnSpecColorChangeListener?.onChanged(data,mProductBean?.color)
                }
            }
        }
    }

    private fun initEvent() {
        startObserve()

        //立即购买
        mBinding.specsProductBuyBtn.setOnClickListener {
            if (checkIsSelectSpecOrColor()){
                val bundle = Bundle()
                bundle.putParcelable(OrderConfirmFragment.BUNDLE_PRODUCT, mProductBean)
                FragmentContainerActivity.start(requireContext(), PageIndex.ORDER_CONFIRM, bundle)
                dismiss()
            }else{
                showSelectSpecOrColorPrompt()
            }
        }

        //加入购物车
        mBinding.specsProductAddBtn.setOnClickListener {
            if (checkIsSelectSpecOrColor()){
                mShopCarVM.addToShopCar(AddShopCarRequest(mProductDetailBean!!.bus_GoodsID,mProductBean!!.color?:"",mProductBean!!.spec?:""))
            }else{
                showSelectSpecOrColorPrompt()
            }
        }
    }

    interface OnSpecColorChangeListener{
        fun onChanged(spec: String?,color: String?)
    }

    fun setOnSpecColorChangeListener(listener: OnSpecColorChangeListener){
        mOnSpecColorChangeListener = listener
    }

    private fun startObserve(){
        //添加到购物车结果
        mShopCarVM.liveAddToShopCar.observe(this, Observer { result ->
            result?.let {
                val(success,msg) = it
                if (success){
                    Toast.makeText(this.context,resources.getString(R.string.added_to_cart),Toast.LENGTH_SHORT).show()
                    EventUtil.post(EventKey.REFRESH_SHOP_CART)
                    EventUtil.post(EventKey.REFRESH_CART_NUM)
                    dismiss()
                }else{
                    Toast.makeText(this.context,msg?:resources.getString(R.string.something_error),Toast.LENGTH_SHORT).show()
                }
            }
        })
    }

    private fun checkIsSelectSpecOrColor(): Boolean{
        return SpecColorUtil.checkIsSelectSpecOrColor(mProductBean,mProductDetailBean)
    }

    private fun showSelectSpecOrColorPrompt(){
        Toast.makeText(this.context,resources.getString(R.string.please_select_spec_or_color),Toast.LENGTH_SHORT).show()
    }
}